package com.ps.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ps.constant.MessageConstant;
import com.ps.context.BaseContext;
import com.ps.dto.*;
import com.ps.entity.*;
import com.ps.exception.AddressBookBusinessException;
import com.ps.exception.OrderBusinessException;
import com.ps.exception.ShoppingCartBusinessException;
import com.ps.mapper.*;
import com.ps.result.PageResult;
import com.ps.service.*;
import com.ps.utils.HttpClientUtil;
import com.ps.utils.WeChatPayUtil;
import com.ps.vo.OrderPaymentVO;
import com.ps.vo.OrderStatisticsVO;
import com.ps.vo.OrderSubmitVO;
import com.ps.vo.OrderVO;
import com.ps.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ps.constant.SystemConstant.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    // 注入地址簿Mapper
    private final AddressBookService addressBookService;
    // 注入购物车Mapper
    private final ShoppingCartService shoppingCartService;
    // 注入订单Mapper
    private final OrderMapper orderMapper;
    // 注入订单明细Mapper
    private final OrderDetailMapper orderDetailMapper;
    private final OrderDetailService  orderDetailService;
    // 注入用户Mapper
    private final UserService userService;
    private final WebSocketServer webSocketServer;
    // 注入店铺地址
    @Value("${ps.shop.address}")
    private String shopAddress;
    // 注入百度地图的ak
    @Value("${ps.baidu.ak}")
    private String ak;
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO orderSubmitDTO) {
        // 根据地址簿id查询地址簿
        AddressBook addressBook = addressBookService.lambdaQuery()
                .eq(AddressBook::getId, orderSubmitDTO.getAddressBookId())
                .one();
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        Long userId = BaseContext.getCurrentId();

        // 查询购物车列表
        List<ShoppingCart> shoppingCartList = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, userId).list();
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 创建订单对象
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDTO, orders);
        orders.setAddress(addressBook.getDetail());
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        save(orders);

        // 创建订单明细列表
        List<OrderDetail> orderDetailList = shoppingCartList.stream()
                .map(cart -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(cart, orderDetail);
                    orderDetail.setOrderId(orders.getId());
                    return orderDetail;
                }).collect(Collectors.toList());

        orderDetailService.saveBatch(orderDetailList);
        // 清空购物车
        shoppingCartService.remove(new LambdaQueryWrapper<ShoppingCart>()
                                .eq(ShoppingCart::getUserId, userId));

        // 构建返回对象
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
    }

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userService.query().eq("id", userId).one();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //根据订单号和用户id查询订单
        Orders ordersDB=
                query().eq("number",ordersPaymentDTO.getOrderNumber())
                .eq("user_id",userId).one();
        //支付成功后，更新订单状态
        paySuccess(ordersDB.getNumber());
        return vo;
    }

    public void paySuccess(String outTradeNo) {
        Long userId = BaseContext.getCurrentId();
        // 根据订单号查询订单
        Orders ordersDB = query().eq( "number", outTradeNo)
                .eq("user_id",userId).one();
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        lambdaUpdate().eq(Orders::getId,ordersDB.getId()).update(orders);
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号"+outTradeNo);
        String json=JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList();
        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id
                // 查询订单明细
                List<OrderDetail> orderDetail = orderDetailService.lambdaQuery()
                        .eq(OrderDetail::getOrderId, orderId).list();
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetail);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new IllegalArgumentException("订单不存在，id: " + id);
        }
        // 查询该订单对应的药品/药品组合明细
        List<OrderDetail> orderDetailList = orderDetailService
                .lambdaQuery().eq(orders.getId()!=null,OrderDetail::getOrderId, orders.getId())
                .list();
        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties( orders,orderVO); // 注意参数顺序：目标在前
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }
    public void userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(id);
        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders,new LambdaQueryWrapper<Orders>().eq(Orders::getId, id));
    }
    public void repetition(Long id) {
            // 查询当前用户id
        Long userId = BaseContext.getCurrentId();
            // 根据订单id查询当前订单详情
        OrderDetail orderDetail = orderDetailMapper.selectById(userId);
        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        BeanUtils.copyProperties(orderDetail,orderDetailList);
        // 将订单详情对象转换为购物车对象
            List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
                ShoppingCart shoppingCart = new ShoppingCart();
                // 将原订单详情里面的药品信息重新复制到购物车对象中
                BeanUtils.copyProperties(x, shoppingCart, "id");
                shoppingCart.setUserId(userId);
                shoppingCart.setCreateTime(LocalDateTime.now());
                return shoppingCart;
            }).collect(Collectors.toList());
            // 将购物车对象批量添加到数据库
        shoppingCartService.saveBatch(shoppingCartList);
    }
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        // 部分订单状态，需要额外返回订单药品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = null;
        try {
            orderVOList = getOrderVOList(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new PageResult(page.getTotal(), orderVOList);
    }
    private List<OrderVO> getOrderVOList(Page<Orders> page) throws Exception {
        // 需要返回订单药品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList =page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderMedicinees = getOrderMedicineesStr(orders);
                // 将订单药品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderMedicinees(orderMedicinees);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }
    private String getOrderMedicineesStr(Orders orders) {
        // 查询订单药品详情信息（订单中的药品和数量）
        List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery()
                .eq(orders.getId()!=null,OrderDetail::getOrderId,orders.getId())
                .list();

        if (orderDetailList == null || orderDetailList.isEmpty()) {
            return ""; // 或者返回 "无药品信息"
        }

        // 将每一条订单药品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderMedicineList = orderDetailList.stream()
                .map(x -> x.getName() + "*" + x.getNumber() + ";")
                .collect(Collectors.toList());

        // 将该订单对应的所有药品信息拼接在一起
        return String.join("", orderMedicineList);
    }
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed =lambdaQuery()
                .eq(Orders::getStatus, Orders.TO_BE_CONFIRMED).count().intValue();
        Integer confirmed = lambdaQuery()
                .eq(Orders::getStatus, Orders.CONFIRMED).count().intValue();
        Integer deliveryInProgress =lambdaQuery()
                .eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS).count().intValue();
        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        lambdaUpdate().eq(Orders::getId,orders.getId()).update(orders);
    }

    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(ordersRejectionDTO.getId());
        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        Orders orders = new Orders();
        if (payStatus == Orders.PAID) {
            orders.setId(ordersDB.getId());
            orders.setStatus(Orders.CANCELLED);
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setCancelTime(LocalDateTime.now());
        }
        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        lambdaUpdate().eq(Orders::getId, orders.getId()).update(orders);
    }
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(ordersCancelDTO.getId());
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        Orders orders = new Orders();
        if (payStatus == 1) {
            orders.setId(ordersCancelDTO.getId());
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason(ordersCancelDTO.getCancelReason());
            orders.setCancelTime(LocalDateTime.now());
        }
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        lambdaUpdate().eq(Orders::getId, orders.getId()).update(orders);
    }
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(id);
        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        lambdaUpdate().eq(Orders::getId, orders.getId()).update(orders);
    }
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(id);
        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        lambdaUpdate().eq(Orders::getId, orders.getId()).update(orders);
    }

    public void reminder(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(id);
        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map=new HashMap();
        map.put("type",2);//1 来单 2催单
        map.put("orderId",id);
        map.put("content","订单号："+ordersDB.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);
        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException(SHOP_PLACE_ERROR);
        }
        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;
        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException(USER_PLACE_ERROR);
        }
        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;
        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");
        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException(PLACE_ERROR);
        }
        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        if (distance > 500000000) {
            //配送距离超过5000米
            throw new OrderBusinessException(GO_ERROR);
        }
    }



}
